<?php
/**
 * Created by PhpStorm.
 * User: trisatria
 * Date: 1/10/14
 * Time: 10:18 AM
 */

namespace Admin\Controller;
use Zend\Authentication\AuthenticationService;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\AdminUserTable;
use Velacolib\Utility\Utility;
class LoginController  extends  AbstractActionController{

    private $userTable;
    private $sm;
    private $service_locator_str;
    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        //login layout
        $this->service_locator_str = 'Admin\Model\AdminUserTable';
        $this->sm = $this->getServiceLocator();
        $this->userTable = $this->sm->get($this->service_locator_str);

        $this->layout('layout/login');
        return parent::onDispatch($e);
    }

    public function  indexAction(){
        $request = $this->getRequest();
        if($request->isPost()){

            $data = $this->params()->fromPost();
            $this->userTable->setLoginUser($data);
            $status = $this->userTable->authenticate();


            $login_obj =  new AuthenticationService(null,$this->userTable);

            $this->userTable->setLoginUser($data);

            $login_obj->authenticate();
                   $user =     $login_obj->getIdentity();
            if($login_obj->hasIdentity() ==1 ){
                if($user->user_type == 1){
                    exit('Access denied!');
                }
                $this->redirect()->toRoute('admin/child',array('controller'=>'topic'));
            }
            else{
                $this->redirect()->toRoute('admin/child',array('controller'=>'login'));
            }
        }
    }

    public function logoutAction(){
        $auth = new AuthenticationService();
        $auth->clearIdentity();
        $this->redirect()->toRoute('admin/child',array('controller'=>'login'));
    }
} 